import java.util.Arrays;

public class Solution1053 {
    public int[] prevPermOpt1(int[] arr) {
        int t=arr.length-1;
        while (t>0 && arr[t]>=arr[t-1]){
            t--;
        }
        if (t==0){
            return arr;
        }
        int m=t-1;
        while (t+1<arr.length && arr[t+1]<arr[m]){
            t++;
        }
        while (arr[t]==arr[t-1]){
            t--;
        }
        int p=arr[m];
        arr[m]=arr[t];
        arr[t]=p;
        return arr;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution1053().prevPermOpt1(new int[]{3, 1, 1, 3})));
    }
}
